#!/usr/bin/python
# -*- coding: utf-8 -*-
# twisted imports
from twisted.words.protocols import irc
from twisted.internet import reactor, protocol
from twisted.python import log
# system imports
import time, sys
import string


class MessageLogger:
    """
    An independent logger class (because separation of application
    and protocol logic is a good thing).
    """
    def __init__(self, file):
        self.file = file

    def log(self, message):
        """Write a message to the file."""
        timestamp = time.strftime("[%H:%M:%S]", time.localtime(time.time()))
        self.file.write('%s %s\n' % (timestamp, message))
        self.file.flush()

    def close(self):
        self.file.close()


class LogBot(irc.IRCClient):
    """A logging IRC bot."""
    import os.path
    from pysqlite2 import dbapi2 as sqlite3
    dbpath = os.path.join(os.path.dirname(__file__), 'db').replace('\\','/') + "/fact.sqlite"
    print dbpath
    global conn, c
    conn = sqlite3.connect(dbpath)
    c = conn.cursor()


    nickname = "pyChao"
    
    def connectionMade(self):
        irc.IRCClient.connectionMade(self)
        self.logger = MessageLogger(open(self.factory.filename, "a"))
        self.logger.log("[connected at %s]" % 
                        time.asctime(time.localtime(time.time())))

    def connectionLost(self, reason):
        irc.IRCClient.connectionLost(self, reason)
        self.logger.log("[disconnected at %s]" % 
                        time.asctime(time.localtime(time.time())))
        self.logger.close()


    # callbacks for events

    def signedOn(self):
        """Called when bot has succesfully signed on to server."""
        self.join(self.factory.channel)

    def joined(self, channel):
        """This will get called when the bot joins the channel."""
        self.logger.log("[I have joined %s]" % channel)

    def irc_JOIN(self, prefix, params):
        user = prefix.split('!', 1)[0]
        if user != self.nickname:
        #    msg = "%s: Hey Hi!" % user
        #    self.msg(params[0], msg)
            pass

    def irc_PART(self, prefix, params):
        user = prefix.split('!', 1)[0]
        if user != self.nickname:
        #    msg = "%s: Bye Bye!" % user
        #    self.msg(params[0], msg)
            pass
    
    def privmsg(self, user, channel, msg):
        """This will get called when the bot receives a message."""
        user = user.split('!', 1)[0]
        self.logger.log("<%s> %s" % (user, msg))
        
        # Check to see if they're sending me a private message
        if channel == self.nickname:
            msg = "It isn't nice to whisper!  Play nice with the group."
            self.msg(user, msg)
            return

        # Otherwise check to see if it is a message directed at me
        #if msg.startswith(self.nickname + ":"):
        #    msg = "%s: Heh guy. Whats up?" % user
        #    self.msg(channel, msg)
        #    self.logger.log("<%s> %s" % (self.nickname, msg))
            
       
        if msg.startswith(".addfact"):
            msg = unicode(msg,'utf8')
            c.execute("INSERT INTO fact (nickname,channel,fact, date) VALUES (?, ?, ?, date('now'))",(user, channel, msg.replace('.addfact ','')))
            msg = "%s: Fact added [#%s]" % (user, c.lastrowid)
            conn.commit()
            self.logger.log("<%s> %s" % (self.nickname, msg))
            self.msg(channel, msg)
            
        if msg.startswith(".fact"):
            fact = c.execute('SELECT fid, nickname, fact from fact ORDER BY Random() LIMIT 1').fetchall()
            #print fact[0][0].decode()
            msg = "[#%s] <%s> %s" % (fact[0][0], fact[0][1], fact[0][2])
            self.msg(channel, msg.encode('utf-8'))
        
        if msg.startswith(".info"):
            msg=string.split(msg)
            if(len(msg)>=2):
                fact = c.execute('SELECT fid, nickname, date, channel from fact where fid='+msg[1]).fetchall()
                msg = "[Fact #%s] Verfasst von %s, Datum: %s im Channel %s" % (fact[0][0],fact[0][1],fact[0][2],fact[0][3])
                self.msg(channel, msg.encode('utf-8'))
            else:
                self.msg(channel, '[Fehler] Parameter fehlt')


    def kickedFrom(self, channel, kicker, message):
        msg = "%s: Heh guy. Whats wrong with you?" % user
        self.msg(kicker, msg)

        
    def action(self, user, channel, msg):
        """This will get called when the bot sees someone do an action."""
        user = user.split('!', 1)[0]
        self.logger.log("* %s %s" % (user, msg))

    # irc callbacks

    def irc_NICK(self, prefix, params):
        """Called when an IRC user changes their nickname."""
        old_nick = prefix.split('!')[0]
        new_nick = params[0]
        self.logger.log("%s is now known as %s" % (old_nick, new_nick))


class LogBotFactory(protocol.ClientFactory):

    # the class of the protocol to build when new connection is made
    protocol = LogBot

    def __init__(self, channel, filename):
        self.channel = channel
        self.filename = filename

    def clientConnectionLost(self, connector, reason):
        """If we get disconnected, reconnect to server."""
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print "connection failed:", reason
        reactor.stop()


if __name__ == '__main__':
    
    # initialize logging
    log.startLogging(sys.stdout)
    channel = "zanzibar"
    logfile = "logs/"+channel+".log"
    # create factory protocol and application
    f = LogBotFactory(channel, logfile)

    
    # connect factory to this host and port
    reactor.connectTCP("chat.freenode.net", 6667, f)

    # run bot
    reactor.run()
